from flask import Flask, request, jsonify, render_template, redirect, url_for, session
from flask_socketio import SocketIO
from config import Config, SOCKETIO_CONFIG
from user_auth import login_required, create_user, verify_user, user_exists, save_user_rating
from rating_system import load_movie_ratings
from video_handler import (
    init_upload_handler, upload_chunk_handler, complete_upload_handler,
    list_videos_handler, select_video_handler, serve_video_handler
)
from socket_handlers import (
    handle_connect, handle_join, handle_disconnect,
    handle_play, handle_pause, handle_seek, handle_sync_status
)

# 初始化应用
app = Flask(__name__, 
            template_folder='../templates',
            static_folder='../static')
app.config.from_object(Config)

# 初始化Socket.IO
socketio = SocketIO(app, **SOCKETIO_CONFIG)

# 用户认证路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    """用户登录"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        if not username or not password:
            return render_template('login.html', error='请输入用户名和密码')
        
        if verify_user(username, password):
            session['username'] = username
            return redirect(url_for('index'))
        else:
            return render_template('login.html', error='用户名或密码错误')
    
    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    """用户注册"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        confirm_password = request.form.get('confirm-password')
        
        if not username or not password or not confirm_password:
            return render_template('register.html', error='请填写所有必填字段')
        
        if password != confirm_password:
            return render_template('register.html', error='两次输入的密码不一致')
        
        if user_exists(username):
            return render_template('register.html', error='用户名已存在')
        
        if create_user(username, password):
            return render_template('register.html', success='注册成功，请登录')
        else:
            return render_template('register.html', error='注册失败，请重试')
    
    return render_template('register.html')

@app.route('/logout')
def logout():
    """用户登出"""
    session.pop('username', None)
    return redirect(url_for('login'))

# 主页面路由
@app.route('/')
def index():
    # 如果用户未登录，重定向到登录页面
    if 'username' not in session:
        return redirect(url_for('login'))
    return render_template('index.html', username=session['username'])

@app.route('/watch')
def watch():
    # 如果用户未登录，重定向到登录页面
    if 'username' not in session:
        return redirect(url_for('login'))
    return render_template('watch.html', username=session['username'])

# 评分相关路由
@app.route('/rating', methods=['POST'])
def submit_rating():
    """提交电影评分"""
    # 检查用户是否登录
    if 'username' not in session:
        return jsonify({'error': '请先登录'}), 401
    
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '缺少评分数据'}), 400
        
        # 验证评分数据
        required_fields = ['overall', 'plot', 'actors', 'sound']
        for field in required_fields:
            if field not in data or not isinstance(data[field], (int, float)) or data[field] < 1 or data[field] > 5:
                return jsonify({'error': f'无效的{field}评分，必须是1-5之间的数字'}), 400
        
        username = session['username']
        from video_handler import room_info
        movie_name = room_info['video_filename'] or '未知电影'
        
        # 保存用户评分到用户数据文件
        user_ratings = {
            'overall': data['overall'],
            'plot': data['plot'],
            'actors': data['actors'],
            'sound': data['sound']
        }
        save_user_rating(username, movie_name, user_ratings)
        
        # 直接从用户文件中重新计算最新的平均评分
        ratings_data = load_movie_ratings(movie_name)
        
        # 通过Socket.IO广播评分更新
        socketio.emit('rating_update', ratings_data, room='main_room')
        
        return jsonify({
            'success': True,
            'message': '评分提交成功',
            'ratings': ratings_data,
            'count': ratings_data['count'],
            'username': username
        })
    except Exception as e:
        print(f"评分提交错误: {str(e)}")
        return jsonify({'error': f'评分提交失败: {str(e)}'}), 500

@app.route('/rating', methods=['GET'])
def get_rating():
    """获取当前电影评分"""
    try:
        from video_handler import room_info
        if room_info['video_filename']:
            ratings_data = load_movie_ratings(room_info['video_filename'])
        else:
            ratings_data = {
                'overall': 0,
                'plot': 0,
                'actors': 0,
                'sound': 0,
                'count': 0
            }
        return jsonify({
            'success': True,
            'ratings': ratings_data,
            'count': ratings_data['count']
        })
    except Exception as e:
        print(f"获取评分错误: {str(e)}")
        return jsonify({'error': f'获取评分失败: {str(e)}'}), 500

# 视频上传相关路由
@app.route('/upload/init', methods=['POST'])
def init_upload():
    return init_upload_handler(app)

@app.route('/upload/chunk', methods=['POST'])
def upload_chunk():
    return upload_chunk_handler(app)

@app.route('/upload/complete', methods=['POST'])
def complete_upload():
    return complete_upload_handler(app, socketio)

# 视频管理相关路由
@app.route('/api/videos', methods=['GET'])
def list_videos():
    return list_videos_handler(app)

@app.route('/api/select-video', methods=['POST'])
def select_video():
    return select_video_handler(app, socketio)

@app.route('/videos/<filename>')
def serve_video(filename):
    return serve_video_handler(app, filename)

# Socket.IO事件
@socketio.on('connect')
def connect_handler():
    handle_connect()

@socketio.on('join')
def join_handler():
    handle_join(socketio, request)

@socketio.on('disconnect')
def disconnect_handler():
    handle_disconnect()

@socketio.on('play')
def play_handler(data):
    handle_play(data)

@socketio.on('pause')
def pause_handler(data):
    handle_pause(data)

@socketio.on('seek')
def seek_handler(data):
    handle_seek(data)

@socketio.on('sync_status')
def sync_status_handler(data):
    handle_sync_status(data)

# 启动应用
if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, debug=True)